package com.cosmoplat.gfqd.processor;

import com.cosmoplat.gfqd.constants.Constants;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 用于基于骨架项目生成新项目后批量修改yml文件
 */
public class BatchUpdateBootstrapYmlFile {

    public static void update() {
        // 获取当前目录的路径
        Path startPath = Paths.get(Constants.PROJECTS_ARCHETYPE_RESOURCES);
        try {
            // 遍历所有目录中的 bootstrap.yml 文件
            List<Path> yamlFiles = findYAMLFilesWithName(startPath, "bootstrap\\.ya?ml");

            // 修改所有找到的 YAML 文件
            for (Path yamlFilePath : yamlFiles) {
                System.out.println("Processing file: " + yamlFilePath);
                updateYAMLFilePreservingComments(yamlFilePath);
            }
        } catch (IOException e) {
            System.err.println("An error occurred while processing YAML files: " + e.getMessage());
        }
    }

    // 遍历目录并找到所有指定名称的 YAML 文件
    private static List<Path> findYAMLFilesWithName(Path startPath, String fileName) throws IOException {
        try (Stream<Path> stream = Files.walk(startPath)) {
            return stream
                    .filter(file -> !Files.isDirectory(file))
                    .filter(file -> file.getFileName().toString().matches(fileName))
                    .collect(Collectors.toList());
        }
    }

    // 修改 YAML 文件，并保留注释
    private static void updateYAMLFilePreservingComments(Path yamlFilePath) {
        try {
            List<String> lines = Files.readAllLines(yamlFilePath);
            List<String> modifiedLines = new ArrayList<>();

            boolean inDeveloperBlock = false; // 用于跟踪是否在 developer 节块中

            for (String line : lines) {
                // 检查是否进入 developer 区块
                if (line.trim().startsWith("developer:")) {
                    inDeveloperBlock = true;
                } else if (!line.startsWith(" ") && !line.isEmpty()) {
                    // 退出 developer 区块（下一个非缩进的块开始）
                    inDeveloperBlock = false;
                }

                // 仅当在 developer 区块中时进行替换
                if (inDeveloperBlock && line.trim().startsWith("nacos-server-addr:")) {
                    line = "  nacos-server-addr: ${nacosServerAddr}";
                }
                if (inDeveloperBlock && line.trim().startsWith("namespace:")) {
                    line = "  namespace: ${nacosNameSpace}";
                }


                // 添加处理后的行
                modifiedLines.add(line);
            }

            // 将修改后的内容写回文件
            Files.write(yamlFilePath, modifiedLines);
            System.out.println("Updated file: " + yamlFilePath);
        } catch (IOException e) {
            System.err.println("An error occurred while updating the file: " + yamlFilePath + " - " + e.getMessage());
        }
    }
}
